import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';

import { MapState, SetBasemapsThumbnail, LoadBasemaps, CheckedBasemaps, basemapsSelector } from '../../store';

import { Basemap } from '../../models';

@Component({
  selector: 'ege-map-basemaps',
  templateUrl: './basemaps.component.html',
  styleUrls: ['./basemaps.component.scss']
})
export class BasemapsComponent implements OnInit {

  basemaps$: Observable<Basemap[]>;
  checked$: Observable<Basemap>;

  constructor(
    private mapStore: Store<MapState>
  ) { }

  ngOnInit() {
    this.mapStore.dispatch(new LoadBasemaps());
    this.basemaps$ = this.mapStore.select(basemapsSelector.getAllBasemaps);
    this.checked$ = this.mapStore.select(basemapsSelector.getCheckedBasemaps);
    this.checked$.subscribe((basemap: Basemap) => {
      basemap && this.mapStore.dispatch(new SetBasemapsThumbnail(basemap.thumbnail));
    });
  }

  onClickBasemap(basemap: Basemap): void {
    this.mapStore.dispatch(new CheckedBasemaps(basemap.id));
    this.mapStore.dispatch(new SetBasemapsThumbnail(basemap.thumbnail));
  }

}
